﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

using WCFMINERP.Contracts;
using WCFMINERP.Contracts.InterFaces;
using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.BLL.TransferBLL;
using System.IO;
using WCFMINERP.COM;
using WCFMINERP.ContextPropagation;


namespace WCFMINERP.Services.TransferFileServers
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single,ConcurrencyMode=ConcurrencyMode.Multiple)]
   
    public class TransferFilesService : ITransferFile
    {
        public static List<UploadInfo> uploadFileInfoList
        {
            get;
            set;
        }
        public TransferFilesService()
        {
            try
            {
                SavePath = _tfsb.GetSavePath();
            }
            catch (Exception ex)
            {
                
            }
        }
        string SavePath = "";
        static int MaxLinkMun = 20;
        TransferFilesServiceBLL _tfsb = new TransferFilesServiceBLL();
        /// <summary>
        /// 获取正在传输文件的列表
        /// </summary>
        /// <returns></returns>
        //public List<TransferFileInfo> GetFilesList()
        //{

        //    return _tfsb.GetFilesList();

        //}
        /// <summary>
        /// 根据文件名字获取文件信息
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns>返回空说明是没有上传过的新文件</returns>
        public TransferFileInfo GetFile(string FileName)
        {
            string SavePath =_tfsb.GetSavePath();
            int intWait=(int)TransferStatus.Wait;
            int intDoing = (int)TransferStatus.Doing;
            TransferFileInfo rtnfile = new TransferFileInfo();
            if (!Directory.Exists(SavePath))
            {
                //提示文件夹打开失败
            }

            if (File.Exists(SavePath + "\\" + FileName))//检查文件是否存在
            {
                FileInfo file = new FileInfo(SavePath + "\\" + FileName);
                UploadInfo  upLoading=_tfsb.GetUploadingFileInfo(FileName);
                if (upLoading != null)//列表中存在就检查是否可以上传并返回
                {
                    if (upLoading.Status == intDoing)//如果是正在上传的可能是由于客户端掉线等状况引起的并且重新连接
                    {
                        ///获取上传文件信息文件部分
                        rtnfile.CreateTime = file.CreationTime;
                        rtnfile.Name = file.Name;
                        rtnfile.Length = upLoading.FileLength;
                        rtnfile.Status = intDoing;
                        rtnfile.Offset = file.Length;//文件实际大小作为偏移量

                        upLoading.LastGuage = file.Length;
                        upLoading.Guage = file.Length;
                        upLoading.LastTime = DateTime.Now;
                        upLoading.SaveTime = DateTime.Now;

                        if (_tfsb.GetTransferingFileCount() > MaxLinkMun)//同时传文件值可以在配置文件或者其他渠道获取
                        {
                            upLoading.Status = intWait;//超过同时传文件最大数量客户端等待
                            rtnfile.Status = intWait;
                        }
                        else
                        {
                            upLoading.Status = intDoing;//未达到同时传文件最大数量客户端可以传输文件
                            rtnfile.Status = intDoing;
                        }
                        EventMonitor.Send(upLoading);
                    }
                    else//如果是等待的
                    {
                        rtnfile.CreateTime = file.CreationTime;
                        rtnfile.Name = file.Name;
                        rtnfile.Length = file.Length;
                        

                        upLoading.LastGuage = file.Length;
                        upLoading.Guage = file.Length;
                        upLoading.LastTime = DateTime.Now;

                        if (_tfsb.GetTransferingFileCount() > MaxLinkMun)//同时传文件值可以在配置文件或者其他渠道获取
                        {
                            upLoading.Status = intWait;//超过同时传文件最大数量客户端等待
                            rtnfile.Status = intWait;
                        }
                        else
                        {
                            upLoading.Status = intDoing;//未达到同时传文件最大数量客户端可以传输文件
                            rtnfile.Status = intDoing;
                        }
                        EventMonitor.Send(upLoading);
                    }
                   
                }
                else//列表中不存在
                {   //重新创建上传列表

                    //该情况逻辑上不会出现
                    
                }
              
            }
            else//文件不存在
            {
                if (!_tfsb.CheckZipRepeated(FileName))//检查是否开过单
                {

                    UploadInfo info = _tfsb.GetUploadingFileInfo(FileName);
                    //未开过单返回文件传输情况
                    rtnfile.CreateTime = Convert.ToDateTime("2000-01-01");
                    rtnfile.Name = FileName;
                    rtnfile.Length = 0;
                    //info.Status=rtnfile.Status = (int)TransferStatus.Wait;
                    
                    info.Guage = 0;
                    info.LastGuage = 0;

                  
                    if (_tfsb.GetTransferingFileCount() > MaxLinkMun)//同时传文件值可以在配置文件或者其他渠道获取
                    {
                        info.Status = rtnfile.Status = (int)TransferStatus.Wait;//超过同时传文件最大数量客户端等待
                    }
                    else
                    {
                        info.Status = rtnfile.Status = (int)TransferStatus.Doing;//未达到同时传文件最大数量客户端可以传输文件
                    }
                    EventMonitor.Send(info);
                    //callBackDisplay.DispalyResult();
                }

            }
           



            return rtnfile;
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="inFile"></param>
        public TransferFileInfo UplodaFile(TransferFileInfo inFile)
        {
            inFile.LastGuage = inFile.Offset;//记录上次偏移量
            inFile.LastTime = inFile.SaveTime;//记录上传保存的时间
            FileStream fs = new FileStream(SavePath + "\\" + inFile.Name, FileMode.OpenOrCreate);//打开文件

            long offset = inFile.Offset;  //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加

            BinaryWriter writer = new BinaryWriter(fs);//初始化文件写入器
            writer.Seek((int)offset, SeekOrigin.Begin);//设置文件的写入位置
            writer.Write(inFile.Data);//写入数据
            inFile.Offset = fs.Length;//返回追加数据后的文件位置
            inFile.SaveTime = DateTime.Now;//记录当前保存时间
            inFile.Data = null;
            writer.Close();
            fs.Close();
            
            UploadInfo upLoading = new UploadInfo();
            upLoading.LastGuage = upLoading.Guage;

            upLoading.LastTime = inFile.LastTime;
            upLoading.SaveTime = DateTime.Now;
            upLoading.Guage = inFile.Offset;
            upLoading.ZipName = inFile.Name;
            inFile.Status=upLoading.Status = (int)TransferStatus.Doing;
            upLoading.CreateTime = inFile.CreateTime;
            upLoading.FileLength = inFile.Length;
            upLoading.ShopName = inFile.ShopName;        
            if (inFile.Offset == inFile.Length)
            {
 
            }
            EventMonitor.Send(upLoading);
            return inFile;//将最新情况返回
        }
       /// <summary>
       /// 初始化上传列表并查看是否可以上传
       /// </summary>
       /// <param name="inFileName"></param>
       /// <param name="fileLength"></param>
       /// <returns></returns>
        public TransferFileInfo InitTransferFile(TransferFileInfo inInfo)
        {            
            string inFileName=inInfo.Name;
            int fileLength = (int)inInfo.Length;
            //string SavePath = _tfsb.GetSavePath();
            //int intWait = (int)TransferStatus.Wait;
            //int intDoing = (int)TransferStatus.Doing;
            TransferFileInfo rtnfile = new TransferFileInfo();
            TransferFileInfo fileInfo = _tfsb.InitTransferFile(inInfo, MaxLinkMun);//检查文件是否可以上传
            //if (fileInfo.Status == intDoing)//文件是可以上传的
            //{
            //    if (File.Exists(SavePath + "\\" + inFileName))//检查文件是否存在
            //    {
            //        FileInfo file = new FileInfo(SavePath + "\\" + inFileName);
            //        rtnfile.CreateTime = file.CreationTime;
            //        rtnfile.Name = file.Name;
            //        rtnfile.Length = fileLength;
            //        rtnfile.Status = intDoing;
            //        rtnfile.Offset = file.Length;
            //        rtnfile.ShopName = fileInfo.ShopName;
            //    }
            //    else
            //    {
            //        rtnfile.CreateTime = fileInfo.CreateTime;
            //        rtnfile.Name = inFileName;
            //        rtnfile.Length = 0;
            //        rtnfile.Status = intDoing;
            //        rtnfile.ShopName = fileInfo.ShopName;
            //    }
            //}
            //else//等待上传
            //{
            //    if (File.Exists(SavePath + "\\" + inFileName))//检查文件是否存在
            //    {
            //        FileInfo file = new FileInfo(SavePath + "\\" + inFileName);
            //        rtnfile.CreateTime = file.CreationTime;
            //        rtnfile.Name = file.Name;
            //        rtnfile.Length = fileLength;
            //        rtnfile.Status = intWait;
            //        rtnfile.Offset = file.Length;
            //        rtnfile.ShopName = fileInfo.ShopName;
            //    }
            //    else
            //    {
            //        rtnfile.CreateTime = fileInfo.CreateTime;
            //        rtnfile.Name = inFileName;
            //        rtnfile.Length = 0;
            //        rtnfile.Status = intWait;
            //        rtnfile.ShopName = fileInfo.ShopName;
            //    }
            //}
            EventMonitor.Send(new UploadInfo() { ShopName = rtnfile.ShopName, CreateTime = rtnfile.CreateTime, Guage = 0, LastGuage = 0, LastTime = DateTime.Now, SaveTime = DateTime.Now, Status = rtnfile.Status, ZipName = rtnfile.Name, FileLength = fileLength });

            return rtnfile;
        }
        /// <summary>
        /// 商户登录获取未完成上传列表
        /// </summary>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public List<TransferFileInfo> GetShopFileList()
        {
            //ApplationParas alpha = (ApplationParas)ApplicationContext.Current.AlphaPara;
            int alpha = (int)ApplicationContext.Current.Shopid;
            return _tfsb.GetFilesList(alpha);
 
        }

        /// <summary>
        /// 完成上传文件
        /// </summary>
        /// <param name="inShopId"></param>
        /// <returns></returns>
        public void EndTransfer(string inFileName)
        {
            _tfsb.CompleteUpload(inFileName);

            UploadInfo upLoading = new UploadInfo();
            upLoading.ZipName = inFileName;
            upLoading.Status = (int)TransferStatus.Done;
            EventMonitor.Send(upLoading);
        }
        /// <summary>
        /// 创建上传记录
        /// </summary>
        /// <param name="inInfo"></param>
        /// <returns>-1错误，0正常，1已经存在</returns>
        public int CreateUploadQueue(TransferFileInfo ininfo)
        {
            return _tfsb.CreateUploadQueue(ininfo);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ininfo"></param>
        /// <returns></returns>
        public int StopUploadQueue(TransferFileInfo ininfo)
        {
            return _tfsb.StopUploadQueue(ininfo);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ininfo"></param>
        /// <returns></returns>
        public int DeleteUploadQueue(TransferFileInfo ininfo)
        {
            return _tfsb.DeleteUploadQueue(ininfo);
        }
    }
}
